package com.endurance.advice;


import com.endurance.compoent.TransactionManager;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
@Aspect
public class ServiceAdvice {

    @Autowired
    TransactionManager transactionManager;
    private Logger logger = LogManager.getLogger(ServiceAdvice.class);

    @Pointcut("execution(* com.endurance.service..*.*(..)))")
    public void pointcut() {

    }

    // 在这里需要设置返回方法的返回值，因为这个切面切的service包下所有的方法，如果不设置返回值，在执行查询方法是返回的可能为空
    @Around("pointcut()")
    public Object aroundServiceAdvice(ProceedingJoinPoint pjp) {
        Object val = null;
        try {
            transactionManager.beginTransaction();
            logger.info("开启事务...");
            logger.info("执行{}目标方法", pjp.getSignature());
            val = pjp.proceed();
            transactionManager.commit();
            logger.info("提交事务...");
        } catch (Throwable e) {
            e.printStackTrace();
            transactionManager.rollback();
            logger.info("回滚事务...");
        } finally {
            transactionManager.release();
            logger.info("释放连接...");
        }
        return val;
    }

}


